package com.ftg.learn.chapter15;

import java.util.*;

/**
	核心思想就是找到回字输出时，行与列的变化规律
*/
public class Huizi{

	/**
		数组的循环输出问题
	*/
	private static void print(String[][] nums){

		int x = nums.length;
		int y = nums[0].length;
		int index = 0;
		int line = 0;
		int direction = 0;
		int x2 = x;
		int y2 = y;

		for (int i = 0, size = x * y; i < size; i++) {

			System.out.print(nums[line][index] + ((i+1) % 4 == 0 ? "\n":" "));
			//上横向处理
	        if (direction == 0) {
	            if (index == x2 - 1) {
	                direction++;
	            } else {
	                index++;
	            }
	        }
			//后纵向处理
	        if (direction == 1) {
	            if (line == y2 - 1) {
	                direction++;
	            } else {
	                line++;
	            }
	        }
			//下横向处理
	        if (direction == 2) {
	            if (index == x - x2) {
	                direction++;
	                y2--;
	            } else {
	                index--;
	            }
	        }
			//前纵向处理
	        if (direction == 3) {
	            if (line == y - y2) {
	                direction = 0;
	                x2--;
	                index++;
	            } else {
	                line--;
	            }
	        }
	    }
	}

	/**
		回字为数组赋值问题
	*/
	private static void print(int x, int y) {
		int index = 0;//列
	    int line = 0;//行
	    int direction = 0;//回字四部分的判断 
	    int x2 = x; //
	    int y2 = y;

	    String[][] arr = new String[y][x];
	    for (int i = 0, size = x * y; i < size; i++) {

	        if (i < 10) {
	            arr[line][index] = "0" + i + "";
	        } else {
	            arr[line][index] = i + "";
	        }

	        checkFlag(direction,index,line,x,y,x2,y2);

	    }

		for(int z = 0;z < arr.length;z++){
			System.out.println(Arrays.toString(arr[z]));
		}

	}

	/**
	 * 把四个方向进行一次封装
	 * @param direction   方向判断问题
	 * @param index       列下标
	 * @param line        行下标
	 * @param x           数组列数
	 * @param y           数组行数
	 * @param x2          用于判断 的行
	 * @param y2          用于判断 的列
	 */
	private static void checkFlag(int direction,int index ,int line,int x,int y, int x2,int y2){
		switch (direction){
			case 0 :
				if (index == x2 - 1) {
					direction++;
				} else {
					index++;
				}
				break;
			case 1 :
				if (line == y2 - 1) {
					direction++;
				} else {
					line++;
				}
				break;
			case 2 :
				if (index == x - x2) {
					direction++;
					y2--;
				} else {
					index--;
				}
				break;
			case 3 :
				if (line == y - y2) {
					direction = 0;
					x2--;
					index++;
				} else {
					line--;
				}
				break;
		}
	}

	public static void main(String[] args){
		//print(5,4);
		String[][] nums = {{"1","2","3","4"},{"5","6","7","8"},{"9","10","11","12"},{"13","14","15","16"}};
		print(nums);
	}

}